import 'dart:convert';
import 'dart:async';
import 'dart:io';
import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import 'package:flutter/services.dart';
import 'package:flutter_aygsh/liz_mine/set/ArticleDetail.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_aygsh/base/Constant.dart';
import 'package:flutter_aygsh/http/Api.dart';
import 'package:flutter_aygsh/http/HttpUtil.dart';
import 'package:wechat_kit/wechat_kit.dart';
import '../base/application.dart';
import 'package:flutter_aygsh/util/LoadingUtil.dart';
import 'Register.dart';
import '../util/SignUtil.dart';
import '../util/AppSaveInfoUtil.dart';
import '../event/LoginEvent.dart';
import './ResetPwd.dart';
import '../util/Toast.dart';
import 'BindWx.dart';

class LoginPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return LoginView();
  }
}

class LoginView extends State<LoginPage> {
  bool isLogin = false, isWxInstall = true, showPhone = true;
  Wechat _wechat = Wechat()
    ..registerApp(
      appId: WX_APPID,
      universalLink: WECHAT_UNIVERSAL_LINK,
    );
  StreamSubscription<WechatAuthResp> _auth;
  WechatAuthResp _authResp;

  TextEditingController schoolController = new TextEditingController();
  TextEditingController userController = new TextEditingController();
  TextEditingController passController = new TextEditingController();
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    checkWx();
    _auth = _wechat.authResp().listen(_listenAuth);
    if (Platform.isAndroid)
      getString("ISAGREE").then((value) {
        if (value == null) {
          show();
        }
      });
  }

  show() {
    showDialog(
        context: context,
        barrierDismissible: false,
        builder: (context) {
          return new WillPopScope(
              onWillPop: () async => false, //重点此举
              child: AlertDialog(
                  title:
                      Text('日尚臻选', style: TextStyle(color: Colors.blueAccent)),
                  content: Container(
                    child: Column(
                      children: <Widget>[
                        Text(
                          '谢谢您使用日尚臻选,我们依据最新的监管要求更新了《用户协议》和《隐私政策》，特向您说明如下：\n1， 为向您提供交易相关的基本功能，我们会收集、使用必要的信息。\n2， 基于您的授权我们可能会获取您的位置等信息，您有权拒绝或取消授权。',
                          style: TextStyle(
                              fontSize: ScreenUtil.getInstance()
                                  .setSp(NORMAL_FONT_SIZE)),
                        ),
                        Container(
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: <Widget>[
                              GestureDetector(
                                behavior: HitTestBehavior.opaque,
                                onTap: () {
                                  Navigator.of(context).push(
                                      MaterialPageRoute(builder: (context) {
                                    return new ArticleDetailPage(
                                      article_id: "2",
                                    );
                                  }));
                                },
                                child: Text(
                                  '《用户协议》',
                                  style: TextStyle(
                                      decoration: TextDecoration.none,
                                      fontSize: ScreenUtil.getInstance()
                                          .setSp(NORMAL_FONT_SIZE),
                                      color: Color.fromARGB(255, 67, 181, 41)),
                                ),
                              ),
                              GestureDetector(
                                behavior: HitTestBehavior.opaque,
                                onTap: () {
                                  Navigator.of(context).push(
                                      MaterialPageRoute(builder: (context) {
                                    return new ArticleDetailPage(
                                      article_id: "14",
                                    );
                                  }));
                                },
                                child: Text(
                                  '《隐私政策》',
                                  style: TextStyle(
                                      decoration: TextDecoration.none,
                                      fontSize: ScreenUtil.getInstance()
                                          .setSp(NORMAL_FONT_SIZE),
                                      color: Color.fromARGB(255, 67, 181, 41)),
                                ),
                              )
                            ],
                          ),
                        ),
                      ],
                    ),
                    height: DP_200,
                  ),
                  actions: <Widget>[
                    FlatButton(
                        child: Text("同意使用"),
                        onPressed: () {
                          saveString("ISAGREE", "1");
                          Navigator.of(context).pop(1);
                        }),
                    FlatButton(
                        child: Text("拒绝",
                            style: TextStyle(
                                color: black_99,
                                fontSize: ScreenUtil.getInstance()
                                    .setSp(NORMAL_FONT_SIZE))),
                        onPressed: () {
                          SystemChannels.platform
                              .invokeMethod('SystemNavigator.pop');
                        })
                  ]));
        });
  }

  checkWx() async {
    // Map map = new Map();
    // map['sign_type'] = SignType.CHECK_VERSION;
    // Response<String> response =
    //     await HttpUtil().post(Api.VERSION_CHECK, data: getSign(map));
    // Map userMap = json.decode(response.data);
    // if (userMap['code'] == 1 && mounted) {
    isWxInstall = await _wechat.isInstalled();
    setState(() {});
    // }
  }

  void _listenAuth(WechatAuthResp resp) {
    _authResp = resp;
    if (_authResp != null &&
        _authResp.errorCode == WechatSdkResp.ERRORCODE_SUCCESS) {
      _wechat
          .getAccessTokenUnionID(
        appId: WX_APPID,
        appSecret: WX_APP_SECRET,
        code: _authResp.code,
      )
          .then((WechatAccessTokenResp accessTokenResp) {
        if (accessTokenResp.errcode == WechatApiResp.ERRORCODE_SUCCESS) {
          _wechat
              .getUserInfoUnionID(
            openId: accessTokenResp.openid,
            accessToken: accessTokenResp.accessToken,
          )
              .then((WechatUserInfoResp userInfoResp) {
            if (userInfoResp.errcode == WechatApiResp.ERRORCODE_SUCCESS) {
              showDialog(
                  context: context,
                  barrierDismissible: false,
                  builder: (_) {
                    return new NetLoadingDialog(
                      loadingText: "检测中...",
                      bgColor: Color.fromARGB(255, 0, 0, 0),
                      requestCallBack: null,
                      outsideDismiss: false,
                    );
                  });
              checkIsWxBind(userInfoResp);
              // _showTips(
              //     '用户信息', '${userInfoResp.nickname} - ${userInfoResp.sex}');
            }
          });
        }
      });
    } else {
      Toast.toast(context, msg: "微信登录失败");
    }
  }

  checkIsWxBind(WechatUserInfoResp resp) async {
    Map map = new Map();
    map['openid'] = resp.openid;
    map['unionid'] = resp.unionid;
    map['type'] = "wx";
    // map['sign_type'] = SignType.CHECK_WX_IS_BIND;
    FormData fromData = FormData.fromMap(new Map<String, dynamic>.from(map));
    Response<String> response =
        await HttpUtil().post(Api.URL_ACCOUNT_CHECKPHONE, data: fromData);
    Map userMap = json.decode(response.data);
    int code = userMap["code"];
    String msg = userMap["msg"];
    Navigator.of(context).pop(1);
    if (msg == '成功，已授权' && mounted) {
      Toast.toast(context, msg: "登录成功");
      saveString(TOKEN, userMap['data']['token']);
      saveString(UID, userMap['data']['uid'].toString());
      saveString(GROUP_ID, userMap['data']['group_id'].toString());
      APPLIC.eventBus.fire(LoginEvent());
      Navigator.of(context).pop();
    } else {
      Toast.toast(context, msg: msg);
      Navigator.of(context).push(new MaterialPageRoute(builder: (context) {
        return new BindWxPage(
          type: "wx",
          unionid: resp.unionid,
          openId: resp.openid,
          nickname: resp.nickname,
          avatar: resp.headimgurl,
          sex: resp.sex.toString(),
        );
      }));
    }
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);
    return new Scaffold(
        appBar: new AppBar(
          title: new Text(
            "登录",
            style: TextStyle(
                fontSize: ScreenUtil.getInstance().setSp(BIG_FONT_SIZE),
                color: Colors.black),
          ),
          elevation: 0.1,
          backgroundColor: Colors.white,
          brightness: Brightness.light,
          centerTitle: true,
          iconTheme: new IconThemeData(color: Colors.white),
        ),
        body: Container(
            color: white,
            child: new ListView(
              children: <Widget>[
                new Column(
                  children: <Widget>[
                    Platform.isIOS
                        ? Container(
                            padding: EdgeInsets.fromLTRB(30, 70, 30, 10),
                            child: GestureDetector(
                              onTap: () {
                                Navigator.of(context).pop();
                              },
                              behavior: HitTestBehavior.opaque,
                              child: Icon(
                                Icons.arrow_back_ios,
                                color: black,
                                size: 30,
                              ),
                            ),
                          )
                        : Center(),
                    loginTopImg(),
                    loginUserEditInput(),
                    new Container(
                      padding: EdgeInsets.fromLTRB(
                          ScreenUtil.getInstance().setWidth(DP_100),
                          0.0,
                          ScreenUtil.getInstance().setWidth(DP_100),
                          0.0),
                      child: Divider(
                        height: 1,
                        color: f0Color,
                      ),
                    ),
                    loginPassEditInput(),
                    new Container(
                      padding: EdgeInsets.fromLTRB(
                          ScreenUtil.getInstance().setWidth(DP_100),
                          0.0,
                          ScreenUtil.getInstance().setWidth(DP_100),
                          0.0),
                      child: Divider(
                        height: 1,
                        color: f0Color,
                      ),
                    ),
                    loginButton(context),
                    loginTip(context),
                    Offstage(
                        offstage: !isWxInstall, child: initMoreLogin(context)),
                    Offstage(
                        offstage: !isWxInstall,
                        child: Padding(
                            padding: EdgeInsets.all(
                                ScreenUtil.getInstance().setHeight(10)),
                            child: new GestureDetector(
                                onTap: () {
                                  if (!isWxInstall) {
                                    Toast.toast(context, msg: "请先安装微信客户端");
                                    return;
                                  }
                                  // print('object');
                                  _wechat.auth(
                                    scope: <String>[
                                      WechatScope.SNSAPI_USERINFO
                                    ],
                                    state: 'auth',
                                  );
                                },
                                child: Column(
                                  children: <Widget>[
                                    Image.asset(
                                      'images/login_wx.png',
                                    ),
                                    Padding(
                                      padding: EdgeInsets.all(10),
                                      child: Text(
                                        '微信登录',
                                        style: TextStyle(fontSize: 14),
                                      ),
                                    )
                                  ],
                                )))),
                  ],
                )
              ],
            )));
  }

  Widget loginTopImg() {
    return new Padding(
        padding: EdgeInsets.all(ScreenUtil.getInstance().setHeight(DP_50)),
        child: Material(
          elevation: 10,
          color: Colors.transparent,
          borderRadius:
              BorderRadius.circular(ScreenUtil.getInstance().setHeight(DP_30)),
          child: new Image.asset(
            'images/logo.png',
            fit: BoxFit.cover,
            width: ScreenUtil.getInstance().setHeight(DP_100),
            height: ScreenUtil.getInstance().setHeight(DP_100),
          ),
        ));
  }

  Widget loginUserEditInput() {
    return new Padding(
      padding: EdgeInsets.fromLTRB(
          ScreenUtil.getInstance().setWidth(DP_100),
          ScreenUtil.getInstance().setHeight(DP_40),
          ScreenUtil.getInstance().setWidth(DP_100),
          0.0),
      child: new Stack(
        alignment: Alignment(1.0, 1.0),
        children: <Widget>[
          new Row(
            children: <Widget>[
              new Padding(
                padding: EdgeInsets.all(5.0),
                child: new Image.asset(
                  "images/icon_phone.png",
                  // scale: 1.8,
                ),
              ),
              Text(' '),
              new Expanded(
                  child: new TextField(
                controller: userController,
                keyboardAppearance: Brightness.light,
                keyboardType: TextInputType.numberWithOptions(),
                maxLines: 1,
                cursorColor: mainColor,
                style: TextStyle(color: Colors.black54),
                decoration: new InputDecoration(
                    hintText: "请输入手机号",
                    border: InputBorder.none,
                    hintStyle: TextStyle(
                        wordSpacing: 0,
                        color: Colors.black38,
                        fontSize:
                            ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE))),
              )),
            ],
          ),
          // new IconButton(
          //     icon: new Image.asset(
          //       "images/del_input.png",
          //       width: ScreenUtil.getInstance().setWidth(DP_20),
          //       height: ScreenUtil.getInstance().setWidth(DP_20),
          //     ),
          //     onPressed: () {
          //       userController.clear();
          //     })
        ],
      ),
    );
  }

  Widget loginPassEditInput() {
    return new Padding(
      padding: EdgeInsets.fromLTRB(
          ScreenUtil.getInstance().setWidth(DP_100),
          ScreenUtil.getInstance().setHeight(DP_20),
          ScreenUtil.getInstance().setWidth(DP_100),
          0.0),
      child: new Stack(
        alignment: Alignment(1.0, 1.0),
        children: <Widget>[
          new Row(
            children: <Widget>[
              new Padding(
                padding: EdgeInsets.all(5.0),
                child: new Image.asset(
                  "images/icon_lock.png",
                  // scale: 1.8,
                ),
              ),
              Text(' '),
              new Expanded(
                  child: new TextField(
                controller: passController,
                cursorColor: mainColor,
                obscureText: true,
                keyboardAppearance: Brightness.light,
                style: TextStyle(color: Colors.black54),
                decoration: new InputDecoration(
                    hintText: "请输入密码",
                    border: InputBorder.none,
                    hintStyle: TextStyle(
                        color: Colors.black38,
                        fontSize:
                            ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE))),
              )),
            ],
          ),
          // new IconButton(
          //     icon: new Image.asset(
          //       "images/del_input.png",
          //       width: ScreenUtil.getInstance().setWidth(DP_20),
          //       height: ScreenUtil.getInstance().setWidth(DP_20),
          //     ),
          //     onPressed: () {
          //       passController.clear();
          //     })
        ],
      ),
    );
  }

  Widget loginButton(BuildContext context) {
    return new Container(
      width: ScreenUtil.getInstance().setWidth(550.00),
      height: ScreenUtil.getInstance().setWidth(DP_90),
      margin: EdgeInsets.fromLTRB(
          0, ScreenUtil.getInstance().setWidth(DP_90), 0, 0),
      decoration: new BoxDecoration(
          color: Color.fromARGB(255, 255, 140, 16),
          borderRadius:
              BorderRadius.circular(ScreenUtil.getInstance().setHeight(DP_80))),
      padding: EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 0.0),
      child: new FlatButton(
        child: new Padding(
          padding: EdgeInsets.all(0.0),
          child: new Text(
            "登录",
            style: new TextStyle(
                color: Colors.white,
                fontSize: ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE)),
          ),
        ),
        onPressed: () {
          _checkSub(context);
        },
      ),
    );
  }

  Widget loginTip(BuildContext context) {
    return new Container(
      width: ScreenUtil.getInstance().setWidth(550.00),
      margin: EdgeInsets.fromLTRB(0, 10, 0, 0),
      child: new Row(
        children: <Widget>[
          Expanded(
            flex: 1,
            child: new GestureDetector(
              child: Text(
                "注册账号",
                style: new TextStyle(
                    color: Colors.grey,
                    fontSize: ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE)),
              ),
              onTap: () {
                toRegister(context);
              },
            ),
          ),
          Expanded(
            flex: 1,
            child: new GestureDetector(
              child: Text(
                "忘记密码?",
                textAlign: TextAlign.right,
                style: new TextStyle(
                    color: Colors.grey,
                    fontSize: ScreenUtil.getInstance().setSp(NORMAL_FONT_SIZE)),
              ),
              onTap: toFindPwd,
            ),
          ),
//
        ],
      ),
    );
  }

  Widget initMoreLogin(BuildContext context) {
    return new Container(
      padding: EdgeInsets.fromLTRB(
          ScreenUtil.getInstance().setWidth(DP_100),
          ScreenUtil.getInstance().setWidth(DP_100),
          ScreenUtil.getInstance().setWidth(DP_100),
          10),
      margin: EdgeInsets.fromLTRB(0, 10, 0, 0),
      child: new Row(
        children: <Widget>[
          Expanded(
            child: Container(
              margin: EdgeInsets.fromLTRB(0, 0, 20, 0),
              height: 1,
              color: f0Color,
            ),
          ),
          Text(
            "更多登录方式",
            textAlign: TextAlign.right,
            style: new TextStyle(color: Colors.grey, fontSize: 14),
          ),
          Expanded(
            child: Container(
              margin: EdgeInsets.fromLTRB(20, 0, 0, 0),
              height: 1,
              color: f0Color,
            ),
          ),
        ],
      ),
    );
  }

  void toFindPwd() {
    Navigator.of(context).push(new MaterialPageRoute(builder: (context) {
      return new ResetPwdPage();
    }));
  }

  void toRegister(BuildContext context) {
    Navigator.of(context).push(new MaterialPageRoute(builder: (context) {
      return new RegisterPage();
    }));
  }

  void _checkSub(BuildContext context) {
    String msgStr = "";
    if (!userController.text.isNotEmpty) {
      msgStr = "用户账号不能为空";
    } else if (!passController.text.isNotEmpty) {
      msgStr = "用户密码不能为空";
    }

    if (msgStr != '') {
      showDialog(
          context: context,
          builder: (context) {
            return new AlertDialog(
              title: new Text("提示信息"),
              content: new Text(msgStr),
              actions: <Widget>[
                new FlatButton(
                    child: new Text("确定"),
                    onPressed: () {
                      Navigator.of(context).pop();
                    }),
              ],
            );
          });
    } else {
      showDialog(
          context: context,
          barrierDismissible: false,
          builder: (_) {
            return new NetLoadingDialog(
              loadingText: "登录中...",
              bgColor: Color.fromARGB(255, 0, 0, 0),
              requestCallBack: null,
              outsideDismiss: false,
            );
          });
      login();
    }
  }

  login() async {
    Map map = new Map.from({
      "sign_type": createSignType(Api.URL_ACCOUNT_LOGIN),
      "account": userController.text,
      "pwd": passController.text
    });
    // getSign(map);
    Response<String> response =
        await HttpUtil().post(Api.URL_ACCOUNT_LOGIN, data: getSign(map));
    Map userMap = json.decode(response.data);
    print(userMap);
    int code = userMap["code"];
    String msg = userMap["msg"];
    Navigator.of(context).pop(1);
    Toast.toast(context, msg: msg);
    if (code == 1) {
      saveString(TOKEN, userMap['data']['token']);
      saveString(UID, userMap['data']['uid'].toString());
      saveString(GROUP_ID, userMap['data']['group_id'].toString());
      saveString(PHONE, userController.text);
      APPLIC.eventBus.fire(LoginEvent());
      Navigator.of(context).pop();
    }
    return true;
  }
}
